﻿using System;
using System.Globalization;
using System.Threading;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using theeg.GraphWpf.Models;

namespace theeg.GraphWpf.Views
{
    public class TransitionToTextGeometryConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Transition transition = value as Transition;
            if (transition == null)
            {
                return null;
            }

            Point startPoint = transition.RoutingPoints[0];
            Point endPoint = transition.RoutingPoints[transition.RoutingPoints.Count - 1];
            GeometryGroup group = new GeometryGroup();
            if (!string.IsNullOrWhiteSpace(transition.SourceText))
            {
                FormattedText text = new FormattedText("" + transition.SourceText,
                                                       Thread.CurrentThread.CurrentUICulture, FlowDirection.LeftToRight,
                                                       new Typeface("Segoe UI"), 12, transition.Brush);

                Geometry textGeometry = text.BuildGeometry(new Point(startPoint.X + 3, startPoint.Y + transition.Magnitude * 0.5 + 6));
                group.Children.Add(textGeometry);
            }
            if (!string.IsNullOrWhiteSpace(transition.TargetText))
            {
                FormattedText text = new FormattedText("" + transition.TargetText,
                                                       Thread.CurrentThread.CurrentUICulture, FlowDirection.LeftToRight,
                                                       new Typeface("Segoe UI"), 12, transition.Brush);

                Geometry textGeometry = text.BuildGeometry(new Point(endPoint.X - 3 - text.Width, endPoint.Y + transition.Magnitude * 0.5 + 6));
                group.Children.Add(textGeometry);
            }
            return group;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
